//关闭提示信息
let notice = document.querySelector('.hint');
notice.addEventListener('click', function () { 
    lkLogin.style.display = 'none';
})

let mod = document.querySelector('.title-two');
let close = document.querySelector('.btn-close');
close.addEventListener('click', function () { 
    mod.style.display = 'none';
})

//页面的连接指向

//判断是否登录
let lkLogin = document.querySelector('.cartnew-tips');
function getName() {
    let userData = localStorage.getItem('username');
    let userShow = document.querySelector('#signin-url');
    let idShow = document.querySelector('#reg-url');
    let cartImg = document.querySelector('.order-pay');
    let cartData = document.querySelector('.showBox');

    

    if (userData == null) {
        userShow.innerText = '[请登录]';
        idShow.innerText = '[免费注册]';
        lkLogin.style.display = 'block';
        cartImg.style.display = 'block';
        cartData.style.display = 'none';
    }
    else {
        // console.log(userData);
        userShow.innerText = userData;
        userShow.style.color = 'black';
        cartData.style.display = 'black';
        lkLogin.style.display = 'none';
        cartImg.style.display = 'none';
        let quit = document.querySelector('#reg-url');
        quit.innerText = '[退出]';
        quit.setAttribute('href', 'javascript:void(0);')
        // 登录调用访问购物车中的数据
        getCharData()
    }
}
getName();


//点击退出

function exit(evt) {
    let e = evt || window.event;
    let exit = document.querySelector('#reg-url');
    console.log(exit.getAttribute('href'))
    if (exit.getAttribute('href') == 'javascript:void(0);') { 
        exit.innerText = '[免费注册]';
        e.preventDefault();
        exit.setAttribute('href', 'login.html')
        // let keys = Object.keys(localStorage);
        localStorage.removeItem('username');
        localStorage.removeItem('token')
        getName();
    }
    
}

//显示和隐藏数据，并显示相关图片
// let without = document.querySelector('.without')
// let tok = localStorage.getItem('token');
// if (tok == null) {
//     without.style.display = 'none'
// }


// 查询数据中购物车的数据


function getCharData() {
    let sum = 0;
    let sopNum = 0;
    let uid = localStorage.getItem('id');
    let charDataUrl = 'http://jx.xuzhixiang.top/ap/api/cart-list.php';
    axios.get(charDataUrl, { params: { id: uid } }).then((r) => {
        // console.log(r.data.data);
        let src = (r.data.data);
        let arr = [];
        for (let key in src) {
            // console.log(src[key].pprice)
            // console.log(src[key].pnum)
            let getStr = `
              <div class="promotion-pool clearfix">
                                <div class="cart-table clearfix">
                                    <ul class="table table-group clearfix">
                                        <li>
                                            <div class="pay-pro td">
                                                <i class="iconfont icon-duigou-weigouxuan icon-gouxuan selected select" onclick="selected(this)" data-role="cart-item-check" data-goodstype="ordinary" checked=""></i>
                                                <a href="../html/item.html?id=${src[key].pid}" class="show-Img"><img src="${src[key].pimg}" alt=""></a>
                                                <p class="pay-pro-info">
                                                    <a href="../html/item.html?id=${src[key].pid}" target="_blank">${src[key].pname}</a>
                                                    <em class="pay-pro-detail"><span>颜色：&nbsp;灰色&nbsp;&nbsp;尺码：&nbsp;XL</span></em>
                                                </p>
                                            </div>
                                            <div class="product-price td">
                                                <p class="p-product-price">
                                                    <span>¥</span>${src[key].pprice}
                                                </p>
                                            </div>
                                            <div class="adjust-cart-num td">
                                                <span class="minus-plus min-num iconfont icon-jianhao" onclick = "pnumChange(${src[key].pid},this)"></span>
                                                <span id="num" class = "num-show">${src[key].pnum}</span>
                                                <span class="minus-plus max-num iconfont icon-jiahao" onclick = "getBtn(${src[key].pid},this)"></span>
                                            </div>
                                            <div class="sub-total red td"><span>¥</span><i class="pri">${((src[key].pprice)*(src[key].pnum))}</i></div>
                                            <div class="cart-operation td">
                                                <span class="cart-del-btn" data-role="cart-del-btn" onclick="delBtn(${src[key].pid},this)">删除</span>
                                                <span class="cart-col-btn" onclick = 'collect()' data-role="cart-mov2fav-btn">移入收藏</span>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                            </div>
            `;
            arr.push(getStr);

            sum += src[key].pprice * src[key].pnum
            sopNum += +(src[key].pnum);
        }
        document.querySelector("#show-box").innerHTML = arr.join("");

        priSum = toMoney(sum)
        $('.num').text(priSum)
        $('.ins').text(sopNum)
    })
}
// getCharData();


//删除商品

function delBtn(pid, obj) {
    $('.loading').css('display', 'block');
    let uid = localStorage.getItem('id');
    let url = "http://jx.xuzhixiang.top/ap/api/cart-delete.php";
    axios.get(url, { params: { pid, uid } }).then((r) => {
        // console.log(r.data.msg)
        if (r.data.msg == '删除成功') {
            obj.parentNode.parentNode.parentNode.parentNode.parentNode.remove();
            $('.loading').css('display', 'none');
            calc();
        } else { 
            alert('r.data.msg');
            $('.loading').css('display', 'none');
        }
        // location.reload();
        // getCharData();
    })
}



//单个商品总计和全部商品的总金额显示


//修改商品数量
function pnumChange(pid, obj) {
    $('.loading').css('display', 'block');
    let pnum = (obj.parentNode.children[1].innerText)
    pnum--;
    // console.log(pnum)
    if (pnum <= 0) {
        delBtn(pid, obj)
    } else { 
        obj.parentNode.children[1].innerText = (pnum);
        fun(pnum,pid,obj)
    }
}

function getBtn(pid, obj) {
    $('.loading').css('display', 'block');
    let pnum = (obj.parentNode.children[1].innerText)
    pnum++;
    // console.log(pnum)
    obj.parentNode.children[1].innerText = (pnum);
    fun(pnum,pid,obj)
}

//发送修改商品请求接口
function fun(pnum,pid,obj) { 
    let uid = localStorage.getItem('id');
    let url = "http://jx.xuzhixiang.top/ap/api/cart-update-num.php";
        axios.get(url,{params:{pid,pnum,uid}}).then((r)=>{
        console.log(r.data)
        if (r.data.msg == '修改成功') { 
            // location.reload();
            // getCharData();
            let sum = Number(obj.parentNode.querySelector('.num-show').innerText)
            console.log(sum)
            let priceOne = (obj.parentNode.previousElementSibling.querySelector('.p-product-price').innerText)
            let priNum = (priceOne.match(/\d+/g));
            // console.log(priNum[0]*sum)
            let priShow = (obj.parentNode.nextElementSibling.querySelector('.pri'))
            console.log('%c [ priShow ]-195', 'font-size:13px; background:pink; color:#bf2c9f;', priShow)
            priShow.innerText = (priNum[0] * sum)
            calc();
        }
    })
}


//结算框显示和置底

window.onscroll = function () {

    let downBox = document.querySelector('.cart-fixed-submit');
    //获取的滚动距离
    let top = document.body.scrollTop || document.documentElement.scrollTop;
    //获取可视区域的高度
    let allTop = document.documentElement.clientHeight;

    let topY2 = downBox.getBoundingClientRect().top;
    console.log('%c [ topY2 ]-222', 'font-size:13px; background:pink; color:#bf2c9f;', topY2)
    // console.log(allTop)
    if (allTop - top > 420 && topY2 >= allTop) {
        downBox.classList.add('fixed-show');
    } else if(allTop - top <= 420){
        downBox.classList.remove('fixed-show');
    }
}

//转换金额格式
function toMoney(num) {
    num = num.toFixed(2);
    num = parseFloat(num)
    num = num.toLocaleString();
    return num;
}

//跳转首页显示
$('.btn-clear').on('click', function () { 
    location.href= '../index.html'
})


//收藏提示
function collect(evt) { 
    alert('已收藏')
}


//全选点击调用函数

$('.selected').toggleClass('icon-gouxuan')

function selectAll(evt) { 
    $('.loading').css('display','block')
    let e = evt || window.event;
    let result = e.target.classList.contains('icon-gouxuan')
    if (result) {
        $('.selected').removeClass('icon-gouxuan');
        // calc();
    } else { 
        $('.selected').removeClass('icon-gouxuan');
        $('.selected').addClass('icon-gouxuan');
        // calc();
    }
    calc();
}



//单个商品前勾选调用函数
function selected(obj) {
    $('.loading').css('display','block')
    let result = (obj.classList.contains('icon-gouxuan'))
    console.log('%c [ result ]-239', 'font-size:13px; background:pink; color:#bf2c9f;', result)
    if (result) {
        obj.classList.remove('icon-gouxuan')
    } else { 
        obj.classList.add('icon-gouxuan')
    }
    calc();
}
//勾选计算金额函数
function calc() { 
    let priNum = 0;
    let soppNum = 0;
    let liAll = document.querySelectorAll('.select');
    // console.log(liAll)
    let str = [];
    liAll.forEach((item) => { 
        let ret = (item.classList.contains('icon-gouxuan'));
        str.push(ret)
    })
    let newArr = Array.from(new Set(str));
    if (newArr.length == 1 && newArr[0] == true) {
        $('.signall').addClass('icon-gouxuan');
    } else {
        $('.signall').removeClass('icon-gouxuan');
    }
    console.log(str)
    //获取数组中为true的商品下标，获取勾选商品中的数据
    for (let key in str) { 
        if (str[key]) { 
            let fu = ((liAll[key].parentNode.parentNode).querySelector('.sub-total'));
            let soppingNum = ((liAll[key].parentNode.parentNode).querySelector('.num-show').innerText);
            let pirceAll = (fu.querySelector('.pri')).innerText
            //获取所有勾选的金额
            priNum += Number(pirceAll);
            //获取勾选商品总数
            soppNum += Number(soppingNum);
        }
    }
    $('.num').text(toMoney(priNum))
    $('.ins').text(soppNum)
    $('.loading').css('display', 'none');
}